import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import FileViewer from '@/components/fileViewer'

import {
    Button,
    DatePicker,
    Form,
    Input,
    Modal,
    Upload,
    message,
    Divider,
    Spin
} from 'antd';
import { InboxOutlined, UploadOutlined } from '@ant-design/icons';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request, useAccess } from 'umi';

const { Dragger } = Upload;
const FileHandleModal = (props: any, refs: any) => {
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState([]);
    const [detailfileList, setdetailfileList] = useState([]);
    const [measureClassData, setmeasureClassData] = useState([]);
    const fileViewer = useRef();
    const { setFieldsValue, resetFields } = form;
    const [code, setCode] = useState('');
    const [uploading, setUploading] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const { TextArea } = Input;
    const {
        listurl = '/plan/work-achievement-upload/allList',
        uploadurl = '/plan/work-package-month/uploadFile',
        deleteurl = '/plan/work-package-month/deleteFile',
        detail = '/plan/work-package-month/downloadFile',
        idkey = 'workPackageMonthId'
    } = props;
    const access = useAccess();
    const globalAuth = access['resultObject'] || {};
    //显示弹窗
    const showModal = () => {
        setIsModalVisible(true);
    };

    //根据字典类型max_file_size获取允许上传的最大文件大小
    const [maxFileSize, setMaxFileSize] = useState(0);
    const [maxFileSizeByte, setMaxFileSizeByte] = useState(0);
    const getMaxFileSize = () => {
        request('/sys/dict/getDictListByType', {
            method: 'POST',
            data: { type: 'max_file_size' },
        }).then((res) => {
            let list = res?.data || [];
            list.map((e, i) => {
                const value = e['value'];
                if (value == '1') {
                    const label = e['label']
                    setMaxFileSize(label)
                    const parsedValue = parseFloat(label); // 将字符串转换为数字   
                    const result = parsedValue * 1024 * 1024; // 获取字节数
                    setMaxFileSizeByte(result)
                }
            });
        });
    };

    useEffect(() => {
        getMaxFileSize();
    }, []);

    //取消
    const handleCancel = () => {
        setIsModalVisible(false);
        setCode('');
        resetFields();
        props.callback && props.callback();
    };
    //确定


    const getDetail = (id: any) => {
        request(listurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            data: {
                [idkey]: id,
            },
        }).then((res) => {
            setdetailfileList(res?.data || [])
            showModal();
        });
    };
    useImperativeHandle(refs, () => ({
        init: (id: any, record: any) => {
            if (id) {
                setCode(id);
                getDetail(id);
            } else {
                showModal();
            }

            // setfileList([]);
        },
    }));
    const handleUpload = async () => {

        setUploading(true);
        const uploadFn = async (item: any) => {
            return new Promise((resolve, reject) => {
                const formData = new FormData();
                formData.append(idkey, code);
                formData.append('file', item);
                request(uploadurl, {
                    method: 'POST',
                    body: formData,
                })
                    .then(() => {

                    })
                    .catch(() => {
                        message.error('上传失败');
                    })
                    .finally(() => {
                        resolve({});
                    });
            })
        }
        for (let i = 0; i < fileList.length; i++) {
            await new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve({});
                }, 600);
            })
            await uploadFn(fileList[i])
        }
        message.success('上传成功');
        setUploading(false);
        setFileList([]);
        getDetail(code);
        // You can use any AJAX library you like

    };
    const uploadprops = {

        onRemove: (file) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
        },
        beforeUpload: (file, filelistss) => {
            setFileList([...fileList, ...filelistss]);
            return false;
        },
        maxCount: 10,
        fileList,
        multiple: true, // 设置为多文件上传  
        customRequest: () => {

        }
        // showUploadList: true,
    };
    const downLoad = (id) => {
        // request(detail + '/' + id, {
        //     method: 'GET',
        //     headers: {
        //         'Content-Type': 'application/json',
        //     },
        //     data: {
        //         [idkey]: id
        //     }
        // }).then((res) => {

        // })
        window.open(`/juyou${detail}/` + id)
    }
    const deleteFn = (id) => {
        Modal.confirm({
            title: '确认删除？',
            content: '',
            onOk() {

                request(deleteurl + '?id=' + id, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    data: {
                        [idkey]: id
                    }
                }).then((res) => {
                    message.success(res?.meta?.msg);
                    getDetail(code);
                })
            },
            onCancel() {
                console.log('Cancel')
            }
        })
    }
    return (
        <Modal
            title={'结果物'}
            visible={isModalVisible}
            onCancel={handleCancel}
            centered
            width={1000}
            maskClosable={false}
            footer={<Button onClick={handleCancel}>关闭</Button>}
            bodyStyle={{
                maxHeight: window.innerHeight - 150,
                overflowY: 'auto',
            }}
        >
            <div>已上传物料<span style={{ fontSize: 'smaller' }}>（若文件无法预览请下载文件后再查看）</span></div>
            <div>
                {
                    detailfileList.map((e: any, i) => {
                        return <div >
                            <span >{e.fileName}</span>

                            <Divider type="vertical" />
                            <a onClick={() => fileViewer.current.init(e)}>预览</a>
                            <Divider type="vertical" />
                            <a onClick={() => downLoad(e.id)}>下载</a>
                            <Divider type="vertical" />
                            {globalAuth['delete'] ? (
                                <a onClick={() => deleteFn(e.id)}>删除</a>
                            ) : (
                                <></>
                            )}

                        </div>
                    })
                }
            </div>
            <hr />
            <div>
                {/* <Upload {...uploadprops}>
                    <Button icon={<UploadOutlined />}>选择文件</Button>
                </Upload>
                 */}
                <Spin spinning={uploading}>
                    <Dragger {...uploadprops}>
                        <p className="ant-upload-drag-icon">
                            <InboxOutlined />
                        </p>
                        <p className="ant-upload-text">点击或者拖动文件至这里上传</p>
                        <p className="ant-upload-hint">
                            支持单次或批量上传
                        </p>
                    </Dragger>
                </Spin>

                <Button
                    type="primary"
                    onClick={handleUpload}
                    disabled={fileList.length === 0}
                    loading={uploading}
                    style={{
                        marginTop: 16,
                    }}
                >
                    {uploading ? '上传中' : '开始上传'}
                </Button>
            </div>
            <FileViewer ref={fileViewer} />
        </Modal>
    );
};
const FileHandleModalCom = forwardRef(FileHandleModal);

export default FileHandleModalCom;
